package com.topscomm.mis.cbb.pm.service.impl;

import com.topscomm.basic.util.PrimaryKeyUtil;
import com.topscomm.mis.cbb.pm.base.pojo.CbbPmProjectEntity;
import com.topscomm.mis.cbb.pm.base.pojo.CbbPmTaskEntity;
import com.topscomm.mis.cbb.pm.base.service.ICbbPmProjectService;
import com.topscomm.mis.cbb.pm.base.service.ICbbPmTaskService;
import com.topscomm.mis.cbb.pm.enumerate.TaskStatusEnum;
import com.topscomm.mis.cbb.pm.service.abs.AbstractProjectService;
import com.topscomm.mis.cbb.pm.service.abs.AbstractTestService;
import com.topscomm.mis.cbb.pm.util.PmSystemConst;
import com.topscomm.mis.cbb.pm.util.ServiceNameUtil;
import com.topscomm.pub.util.ConvertUtil;
import com.topscomm.pub.util.SpringUtil;
import com.topscomm.pub.util.StringBufferProxy;
import com.topscomm.pub.util.StringUtil;
import com.topscomm.tap.TapService;
import com.topscomm.tap.common.SessionUserBean;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class ProjectService extends AbstractProjectService {

    @Autowired
    private ICbbPmProjectService cbbPmProjectService;
    @Autowired
    private ICbbPmTaskService cbbPmTaskService;

    @Override
    public String generateProjectUuCode() {
        StringBuilder uuCode = new StringBuilder();
        //PRO
        uuCode.append(PmSystemConst.CodePrefix.UUCODE);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        String day = simpleDateFormat.format(calendar.getTime());
        //yyMMdd
        uuCode.append(day.substring(2));
        StringBufferProxy sql = new StringBufferProxy();
        // 查询当前最大编号
        List<String> fieldList = new ArrayList<String>();
        //PRO23061600001
        fieldList.add("max(to_number(substr(" + CbbPmProjectEntity.FieldCode + ",10,5))) as nums");
        // 公共项目表叫做code
        sql.appendLineSingle(" {0} like '{1}%'", CbbPmProjectEntity.FieldCode, uuCode.toString());
        List<Map<String, Object>> maps = cbbPmProjectService
            .queryMapFieldsByWhere(sql.toString(), fieldList);
        if (maps.size() > 0 && maps.get(0) != null) {
            int nums = ConvertUtil.convertToInt(maps.get(0).get("nums")) + 1;
            String numstr = ConvertUtil.convertToString(nums);
            int length = numstr.length();
            if (length < 5) {
                for (int i = 0; i < 5 - length; i++) {
                    numstr = "0" + numstr;
                }
            }
            uuCode.append(numstr);
        } else {
            // 如果不存在，默认为00001
            uuCode.append("00001");
        }
        return uuCode.toString();
    }

    /***
     * @description: 项目废弃
     * @param paramMap
     * @return void
     * @author: wangxinhua
     * @date: 2023/6/25 11:48
     * @modify:
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void abandon(Map<String, Object> paramMap, SessionUserBean sessionUserBean) {
        CbbPmProjectEntity pmProjectEntity = cbbPmProjectService.queryObjectByWhere(CbbPmProjectEntity.FieldCode +"'"+ConvertUtil.convertToString(paramMap.get("code"))+"'");
        //作废状态
        pmProjectEntity.setState(PmSystemConst.ProjectState.ABANDON);
        cbbPmProjectService.updateEntity(pmProjectEntity);
        //更新所有未开始,未完成的任务为取消
        List<Integer> notCompleteStatus = Arrays.asList(PmSystemConst.TaskStatus.NOTSTART, PmSystemConst.TaskStatus.READYSTART, PmSystemConst.TaskStatus.RUNNING, PmSystemConst.TaskStatus.CONFUSION);
        StringBufferProxy nodeNotCompleteSql = new StringBufferProxy();
        nodeNotCompleteSql.appendSingle(" {0}='{1}' ", CbbPmTaskEntity.FieldProjectuucode, pmProjectEntity.getCode());
        nodeNotCompleteSql.appendSingle(" and {0} in ({1}) ", CbbPmTaskEntity.FieldStatus, StringUtils.join(notCompleteStatus, ","));
        Map<String, Object> updateMap = new HashMap<>();
        updateMap.put(CbbPmTaskEntity.FieldStatus, TaskStatusEnum.CANCEL.getNumber());
        cbbPmTaskService.updateByWhere(updateMap, nodeNotCompleteSql.toString());

        //取消所有未审批完成的审批流
        nodeNotCompleteSql.clear();
        nodeNotCompleteSql.appendSingle(" {0}='{1}' and NODEINSID is not null ", CbbPmTaskEntity.FieldProjectuucode, pmProjectEntity.getCode());
        List<Map<String, Object>> flowIns = cbbPmTaskService.queryMapByWhere(nodeNotCompleteSql.toString(),"queryTaskFlowIns");
        for (Map<String, Object> flowIn : flowIns) {
            String serviceName = ServiceNameUtil.getNameBySourceType(ConvertUtil.convertToString(flowIn.get("sourcetype")));
            TapService tapService = (TapService) SpringUtil.getBean(serviceName);
            tapService.executeDelApprove(ConvertUtil.convertToString(flowIn.get("sourceid")), sessionUserBean);
        }
    }
    /**
     * description 根据项目号查询项目
     * @author wxm
     * @date 2023-06-25 19:11:40
     * @param projectCode
     * @return java.util.List<java.util.Map<java.lang.String,java.lang.Object>>
     * @modify
     */
    @Override
    public List<Map<String, Object>> queryProjectByCode(String projectCode) {

        return cbbPmProjectService
            .queryMapByWhere(CbbPmProjectEntity.FieldCode + " = '" + projectCode + "'");
    }
}
